<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2023/8/21
 * Time: 22:19
 */

namespace app\backstage\logic;


use app\common\model\RechargeActivity;
use app\common\model\RechargeItem;
use think\Db;

class RechargeLogic
{

    /**
     * 充值项列表
     * @param $where
     * @return \think\response\Json
     */
    public function itemListArray($uid)
    {
        $quick_id = Db::table('quick_app_mp_manager')->where('uid',$uid)->field('quick_id')->findOrEmpty();
        if(empty($quick_id))
        {
            return errJson('该账号未授权App');
        }

        $where[] = ['quick_id','=',$quick_id['quick_id']];
        $where[] = ['is_activity', '=', 0];
        $where[] = ['manage_id', '=', $uid];
        $where[] = ['delete_time','<',1];

        $list = Db::table('pay_recharge_item')->where($where)->select();

        if(empty($list))
        {
            $where_m[] = ['quick_id','=',$quick_id['quick_id']];
            $where_m[] = ['is_activity', '=', 0];
            $where_m[] = ['manage_id', '=', 0];
            $where_m[] = ['delete_time','<',1];

            $list = Db::table('pay_recharge_item')->where($where_m)->select();
        }

        foreach ($list as $k=>$v)
        {
            $list[$k]['totalFeeText'] = $v['total_fee'] / 100;
        }

        return $list;
    }

    /**
     * 充值项列表
     * @param $where
     * @return \think\response\Json
     */
    public function itemList($where)
    {
        $list = RechargeItem::getList($where, '*', 'sort asc,id asc');
        foreach ($list as $k => $v) {
            $list[$k]['totalFeeText'] = $v->total_fee_text;
        }
        return sucJson($list);
    }

    /**
     * 活动列表
     * @param $where
     * @param $page
     * @param $limit
     * @return \think\response\Json
     */
    public function activityList($where, $page, $limit)
    {
        $role = request()->_role;
        $user = request()->_user;
        $model = new RechargeActivity();
        $query = $model->where($where)->where(function ($query) use ($role, $user) {
            if ($role->alias == 'agent') {
                $query->where("agent_id", $user->id)->whereOr(function ($query) {
                    $query->where("agent_id", 0);
                });
            } else {
                $query->where("agent_id", 0);
            }
        });
        $count = $query->count();
        $list = $query->with(['item'])->order("id desc")->page($page, $limit)->select();
        foreach ($list as $k => $v) {
            $list[$k]['item']['totalFeeText'] = $v['item']->total_fee_text;
            $list[$k]['img_text'] = $v->img_text;
            $list[$k]['pop_img_text'] = $v->pop_img_text;
            $list[$k]['allow'] = 1;
            if (($role->alias == 'agent' || $role->alias == 'channel') && $v->agent_id != $user->id) {
                $list[$k]['allow'] = 0;
            }
        }
        return sucJson($list, $count);
    }



    /**
     * 能使用的所有活动
     * @param $where
     * @return RechargeActivity[]|\think\Collection
     */
    public static function allActivity($where = [])
    {
        $role = request()->_role;
        $user = request()->_user;
        $model = new RechargeActivity();
        $query = $model->where($where)->where(function ($query) use ($role, $user) {
            if ($role->alias == 'agent') {
                $query->where("agent_id", $user->id)->whereOr(function ($query) {
                    $query->where("agent_id", 0);
                });
            } else {
                $query->where("agent_id", 0);
            }
        });
        $list = $query->with(['item'])->order("id desc")->select();
        return $list;
    }


    /**
     * 设置活动
     * @param $data
     * @param int $id
     * @return \think\response\Json
     */
    public function setActivity($data, $id = 0)
    {
        if (isset($data['total_fee'])) {
            $data['total_fee'] = $data['total_fee'] * 100;
        }
        $role = request()->_role;
        $user = request()->_user;
        if ($id) {
            $activity = RechargeActivity::get($id);
            if (!$activity) {
                return errJson('活动不存在');
            }
            if ($role->alias == 'agent' && $activity->agent_id != $user->id) {
                return errJson('无权限修改此活动');
            }
            RechargeItem::where('id', $activity->item_id)->update([
                'total_fee' => $data['total_fee'],
                'virtual_currency' => $data['virtual_currency'],
                'point_gift' => $data['point_gift'],
                'vipdays' => $data['vipdays'],
            ]);
            $field = ['title', 'img_url', 'pay_times','pop_img'];
            $activity->allowField($field)->save($data);
        } else {
            $itemId = RechargeItem::insertGetId([
                'total_fee' => $data['total_fee'],
                'virtual_currency' => $data['virtual_currency'],
                'point_gift' => $data['point_gift'],
                'vipdays' => $data['vipdays'],
                'is_activity' => 1,
            ]);
            $data['item_id'] = $itemId;
            $field = ['title', 'img_url', 'agent_id', 'item_id', 'pay_times','pop_img'];
            if ($role->alias == 'agent') {
                $data['agent_id'] = $user->id;
            }
            $activity = new RechargeActivity();
            $activity->allowField($field)->save($data);
        }
        return sucJson();
    }

    /**
     * 删除活动（软删除）
     * @param $id
     * @return \think\response\Json
     */
    public function delActivity($id)
    {
        $activity = RechargeActivity::get($id);
        if (!$activity) {
            return errJson('活动不存在');
        }
        $role = request()->_role;
        $user = request()->_user;
        if ($role->alias == 'agent' && $activity->agent_id != $user->id) {
            return errJson('无权限删除此活动');
        }
        $item = RechargeItem::get($activity->item_id);
        $item->delete();
        $activity->delete();
        return sucJson();
    }
}